package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import service.ProductService;
import util.DownUtils;

/**
 * Servlet implementation class DownloadServlet
 */
public class DownloadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 获取下载的条件
		String year =request.getParameter("year");
		String month =request.getParameter("month");	
		//调用service
		ProductService service =new ProductService();
		//要查询下载的数据，已完成支付的商品信息
		List<Object[]> ps=service.download(year,month);
		String fileName =year+"年"+month+"月销售榜单.csv";
		String fileType =this.getServletContext().getMimeType(fileName);
		//设置文件响应头
		response.setContentType(fileType);
		//设置下载框的响应头
		response.setHeader("Content-Disposition","attachment;fileName="+DownUtils.filenameEncoding(fileName, request));
		//写到文件里
		PrintWriter out=response.getWriter();
		out.print("商品名称,商品数量");
		for (int i = 0; i < ps.size(); i++) {
			Object[] arr=ps.get(i);
			out.println(arr[0]+","+arr[1]);
		}
		out.flush();
		out.close();
	}

}
